package com.demo;

import org.apache.hadoop.io.Text;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//自定义异常类
class LineException extends Exception{
    private static final long serialVersionUID = 8245008693589452584L;
    int flag;
    public LineException(String msg,int flag){
        super(msg);
        this.flag = flag;
    }
    public int getFlag()
    {
        return flag;
    }
}
public class TableLine {
    private String imsi,position,time,timeFlag;
    private Date day;
    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public void set(String line,String date,String[] timepoint) throws LineException{
        String[] lineSplit = line.split("\t");

            this.imsi = lineSplit[0];
            this.position = lineSplit[2];
            this.time = lineSplit[3];

        if( !this.time.startsWith(date)) //检查时间是否与输入的相同
        {
            throw new LineException("",-1);//与输入时间不同，flag是-1
        }
        try
        {
            this.day = this.formatter.parse(this.time);//按照formatter的格式来解析输入的time格式
        }
        catch(ParseException e)
        {
            throw new LineException("",0);//格式不对，flag是0
        }
        //下面是判断时间是否在指定的时间段里面
        int i = 0, n = timepoint.length;//数组中的元素个数
        int hour = Integer.valueOf(this.time.split(" ")[1].split(":")[0]);//yyyy-MM-dd HH:mm:ss 提取HH
        while (i < n && Integer.valueOf(timepoint[i] ) <= hour)
            i++;
        if(i<n)
        {
            if(i == 0)
                this.timeFlag = ("00-" + timepoint[i]);//判断是否在时间段之前，然后输出时间段
            else
                this.timeFlag = ( timepoint[i-1]+"-"+timepoint[i]);
        }
        else
            throw new LineException("",-1);//不是在指定的时间段里面
    }

    public Text outKey(){
        return new Text (this.imsi + "|"+ this.timeFlag);
    }

    public Text outValue(){
        long t =( day.getTime() / 1000L ); //用一个UNIX的时间，getTime本身就是返回一个unix的时间
        return new Text(this.position + "|" + String.valueOf(t));
    }
}
